package com.lfs.feishu.controller;

import com.alibaba.fastjson.JSON;
import com.lark.oapi.service.authen.v1.resource.UserInfo;
import com.lfs.feishu.domain.response.FeishuResponse;
import com.lfs.feishu.domain.response.TokenResponse;
import com.lfs.feishu.domain.response.UserInfoResponse;
import com.lfs.feishu.service.UserInfoService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.google.gson.JsonParser;
import com.lark.oapi.Client;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.service.authen.v1.model.*;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import com.lark.oapi.core.request.RequestOptions;

import static com.lfs.feishu.constant.AppInfo.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/oauth")
@AllArgsConstructor
public class LoginController {
    RestTemplate restTemplate;
    UserInfoService userInfoService;


    @GetMapping("/feishu/callback")
    public void userInfo() throws Exception {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String fullPath = request.getRequestURI();
        log.info("fullPath={}", fullPath);
        String state = request.getParameter("state");
        String authCode = request.getParameter("code");
        log.info("回调开始，授权码code={}", authCode);
        // 1. 设置请求头 (Headers)
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 2. 设置请求体 (Body)
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("grant_type", "authorization_code");
        requestBody.put("client_id", APP_ID);
        requestBody.put("client_secret", APP_SECRET);
        requestBody.put("code", authCode);
        requestBody.put("redirect_uri", "http://localhost:4399/oauth/feishu/callback");
        // 3. 组合请求头和请求体为 HttpEntity

        ResponseEntity<String> responseEntity;
        try {
            responseEntity = restTemplate.postForEntity(
                    "https://open.feishu.cn/open-apis/authen/v2/oauth/token",
                    new HttpEntity<>(requestBody, headers),
                    String.class // 期望响应体是 String 类型
            );
        } catch (Exception e) {
            log.error("请求飞书API时发生错误", e);
            return;
        }
        String body = responseEntity.getBody();
        TokenResponse tokenResponse = JSON.parseObject(body, TokenResponse.class);
        String accessToken = tokenResponse.getAccess_token();
        log.info("用户token：{}", accessToken);

        FeishuResponse feishuResponse = userInfoService.getByToken(accessToken);
        UserInfoResponse data = feishuResponse.getData();
        log.info("用户信息：{}", data);
//        return new ModelAndView(authCode);
    }

}
